package com.xunji.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xunji.user.common.BaseException;
import com.xunji.user.common.ResultCodeEnum;
import com.xunji.user.dto.MenuDto;
import com.xunji.user.entity.Menu;
import com.xunji.user.mapper.MenuMapper;
import com.xunji.user.service.MenuService;
import com.xunji.user.util.MenuUtil;
import com.xunji.user.vo.rep.MenuQueryResponse;
import com.xunji.user.vo.req.MenuAddRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Override
    public void addMenu(MenuAddRequest request) {
        this.save(Menu.getInstance(request));
    }

    @Override
    public MenuQueryResponse getMenus() {
        List<MenuDto> menuDtos = list().stream().map(MenuDto::getInstance).collect(Collectors.toList());
        List<MenuDto> tree = MenuUtil.makePidTree(menuDtos, 0);
        MenuQueryResponse response = new MenuQueryResponse();
        response.setMenus(tree);
        return response;
    }

    @Override
    public void deleteById(Integer id) {
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("p_id", id);
        if (!CollectionUtils.isEmpty(this.list(queryWrapper))) {
            throw new BaseException(ResultCodeEnum.NODE_CAN_NOT_DELETE);
        }
        this.removeById(id);
    }

    @Override
    public List<Menu> selectByName(String name) {
        QueryWrapper<Menu> qw = new QueryWrapper<>();
        qw.eq("name", name);
        return baseMapper.selectList(qw);
    }

    @Override
    public List<Menu> getMenusByIds(List<Integer> ids) {
        QueryWrapper<Menu> qw = new QueryWrapper<Menu>().in("id", ids);
        return list(qw);
    }
}
